import { useState, useEffect } from "react";
import { Col, Row, Alert } from "react-bootstrap";

export const Newsletter = (status,message,onValidated) => {
    // email 默认空字符串
    const [email,setEmail] = useState('')

    // 判断只是成功后才清空邮箱,传值staus判断
    useEffect(() => {
        if (status === 'success') clearFields();
    },[status])

    // 表单提交
    const handleSubmit = (e) => {
        // 阻止默认事件
        e.preventDefault();
        // 检查是否输入，是否包括@，是否已经订阅
        email && email.indexOf("@") > -1 && onValidated({
            EMAIL:email
        })
    }

    // 成功后将表单清空
    const clearFields = () => {
        setEmail('')
    }

    return (
        <Col lg={12}>
            <div className="newsletter-bx wow slideInUp">
                <Row>
                    <Col lg={12} md={6} xl={5}>
                        <h3>订阅我们<br /> & 不要错过我们的更新</h3>
                        {status === 'sending' && <Alert>发送中...</Alert>}
                        {status === 'error' && <Alert variant="danger">{message}</Alert>}
                        {status === 'success' && <Alert variant="success">{message}</Alert>}

                    </Col>
                    <Col md ={6} xl={7}>
                        <form onSubmit={handleSubmit}>
                            <div className="new-email-bx">
                                <input value={email} type="email" onChange={(e)=> setEmail(e.target.value)} placeholder="邮箱地址" />
                                <button type="submit">提交</button>
                            </div>
                        </form>
                    </Col>
                </Row>
            </div>
        </Col>
    )
}